package com.example.floristshop.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.os.FileUtils;
import android.util.Log;
import android.view.View;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class SaveAsPicUtil {
    public static void save(Context context, String name, View view){
        Bitmap bitmap = viewToBitmap(view);
        saveBitmap(name, bitmap, context);
    }

    private static Bitmap viewToBitmap(View view){
        Bitmap bitmap =Bitmap.createBitmap(view.getWidth(),view.getHeight(),Bitmap.Config.ARGB_8888);
        Canvas c= new Canvas(bitmap);
        c.translate(-view.getScaleX(),-view.getScrollY());
        view.draw(c);
        return bitmap;
    }

    private static void saveBitmap(String name, Bitmap bm, Context mContext) {
        Log.d("lyc", "Ready to save picture");
        //指定我们想要存储文件的地址
        String TargetPath = mContext.getExternalMediaDirs()[0]+"/";
        Log.d("lyc", "Save Path=" + TargetPath);
        //判断指定文件夹的路径是否存在
        if (!fileIsExist(TargetPath)) {
            Log.d("lyc", "TargetPath isn't exist");
        } else {
            //如果指定文件夹创建成功，那么我们则需要进行图片存储操作
            File saveFile = new File(TargetPath, name);

            try {
                FileOutputStream saveImgOut = new FileOutputStream(saveFile);
                // compress - 压缩的意思
                bm.compress(Bitmap.CompressFormat.JPEG, 80, saveImgOut);
                //存储完成后需要清除相关的进程
                saveImgOut.flush();
                saveImgOut.close();
                Log.d("Save Bitmap", "The picture is save to your phone!");
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    private static boolean fileIsExist(String fileName)
    {
        //传入指定的路径，然后判断路径是否存在
        File file=new File(fileName);
        if (file.exists())
            return true;
        else{
            //file.mkdirs() 创建文件夹的意思
            return file.mkdirs();
        }
    }
}
